<template>
  <div>

    <div class="main">
      <div style="padding-top: 2%; padding-left: 2%; padding-right: 2%">
        <div class="title" >
           <vue-mathjax :formula="paper.title" :safe="false"></vue-mathjax>
        </div>

        <div class="line0">
          <span
            class="author"
            v-for="(author, index) in paper.authors"
            :key="index"
            @click="ToUserPage(author)"
          >
            {{ author.name }},
          </span>
        </div>

        <div class="line1">
          <span style="margin-right: 1%; color: #42b983"
            >被引用: {{ paper.n_citation }}</span
          >
          <span>|</span>
          <span style="margin-left: 1%; color: blue">
            浏览: {{ this.paper.view_num }}</span
          >
        </div>

        <div class="line2">
          <v-btn
            @click="ToPDF"
            style="background-color: #5084c3; color: white; margin-right: 1%"
            :disabled="!this.paper.pdf"
            >下载PDF</v-btn>

<!--          <v-btn-->
<!--              -->
<!--            style="background-color: #006b89; color: white; margin-right: 1%"-->
<!--            >引用</v-btn-->
<!--          >-->
          <v-dialog
              v-model="dialog"
              width="500"
          >
            <template v-slot:activator="{ on, attrs }">
              <v-btn
                  color="red lighten-2"
                  dark
                  v-bind="attrs"
                  v-on="on"
              >
                引用
                <v-icon
                  small
                >
                  {{icons.mdiComma}}
                </v-icon>
              </v-btn>

            </template>

            <v-card>
              <v-card-title class="text-h5 grey lighten-2;" >
                引用
              </v-card-title>

              <v-card-text>
                <h3 style="margin-top: 1%">MLA:</h3>
                <div>{{this.cite.MLA ? this.cite.MLA[0] : 0}}</div>
                <h3 style="margin-top: 2%">APA:</h3>
                <div>{{this.cite.APA ? this.cite.APA[0] : 0}}</div>
                <h3 style="margin-top: 2%">GB/T 7714:</h3>
                <div>{{this.cite.GB ? this.cite.GB[0] : 0}}</div>
              </v-card-text>


              <v-divider></v-divider>

              <v-card-actions>
                <v-spacer></v-spacer>
                <v-btn
                    style="background-color: #006b89; color: white; "
                    text
                    @click="dialog = false"
                >
                  取消
                </v-btn>
              </v-card-actions>
            </v-card>
          </v-dialog>

          <v-btn
            v-if="is_collected"
            style="background-color: #589bad; color: white; margin-left: 1%"
            @click="remove_collect"
            >取消收藏</v-btn
          >

          <v-btn
            v-else
            style="background-color: #02206d; color: white; margin-left: 1%"
            @click="collect"
            >收藏</v-btn
          >
        </div>

        <div class="line3">
          <p
            style="
              margin-top: 1%;
              margin-bottom: 0.5%;
              color: #131120;
              font-size: 20px;
            "
          >
            关键词
          </p>
          <v-btn
            v-for="(item, index) in paper.keywords"
            :key="index"
            class="keyword_btn"
            text
            outlined
            color="primary"
            @click="keywordSearch(item)"
            >{{ item }}</v-btn
          >
        </div>

        <div class="line4">
          <p style="color: #131120; font-size: 20px; margin-bottom: 0.5%">
            摘要
          </p>
          <p style="color: #5e5669">
            <vue-mathjax :formula="paper.abstract" :safe="false"></vue-mathjax>
          </p>
        </div>

        <v-tabs
          v-model="tab"
          background-color="transparent"
          color="primary"
          grow
        >
          <v-tab :key="0"> 预览PDF </v-tab>

          <v-tab :key="1"> 引用论文 </v-tab>

          <v-tab :key="2" @click="initLikesList"> 评论区 </v-tab>

          <v-tab :key="3"> 论文速读 </v-tab>
          <v-tab-item>
            <div
              v-if="pageTotalNum > 0"
              style="background-color: mediumpurple; min-height: 30px"
            >
              <v-btn
                style="margin-left: 1%; color: mediumpurple"
                type="primary"
                x-small
                @click="prePage"
              >
                上一页
              </v-btn>

              <v-btn
                style="margin-left: 1%; color: mediumpurple"
                type="primary"
                x-small
                @click="nextPage"
              >
                下一页
              </v-btn>

              <div style="color: white; float: right; margin-right: 2%">
                Page: {{ pageNum }} / {{ pageTotalNum }}
              </div>
            </div>

            <h1
              v-else
              style="text-align: center; margin-top: 25%; margin-bottom: 30%"
            >
              暂无相关数据！
            </h1>

            <pdf
              ref="pdf"
              :src="this.paper.pdf"
              :page="pageNum"
              @progress="loadedRatio = $event"
              @num-pages="pageTotalNum = $event"
            ></pdf>
          </v-tab-item>

          <v-tab-item style="margin-bottom: 1%">
            <div v-if="paper.references && paper.references.data && paper.references.data[0]">
              <div
                v-for="(item, index) in paper.references.data"
                :key="index"
                style="margin-left: 1%; margin-top: 0.5%; margin-right: 1%"
              >
                <span style="color: black">{{ index + 1 }}.</span>

                <!--              作者-->
                <span
                  class="author_of_references"
                  v-for="(author, index) in item.authors"
                  :key="index"
                  @click="ToUserPage(author)"
                >
                  {{ author.name }},
                </span>

                <span class="title_of_reference" @click="toPaperDetail(item)">
                  {{ item.title }}
                </span>

                <span style="color: black"
                  >被引用: {{ item.num_citation }},</span
                >

                <span>&nbsp;{{ item.year }}</span>
              </div>
            </div>

            <h1
              v-else
              style="text-align: center; margin-top: 10%; margin-bottom: 10%"
            >
              暂无相关数据!
            </h1>
          </v-tab-item>

          <!--          评论区-->
          <v-tab-item>
            <div style="margin: 0.5% 3% 1% 2%">
              <h1>评论</h1>

              <!--              <div-->
              <!--                  v-for="(comment,index) in this.comment_list"-->
              <!--                  :key="index"-->
              <!--              >-->
              <!--                <div style="display: inline-block">-->
              <!--                  <v-avatar-->
              <!--                      tile-->
              <!--                      rounded-->
              <!--                      style="background-color: lightgray"-->
              <!--                  >-->
              <!--                    {{comment_user_list[index].username}}-->
              <!--                    &lt;!&ndash;                    <img :src="this.comment_user_list[index].avatar" alt="ABC">&ndash;&gt;-->
              <!--                  </v-avatar>-->
              <!--                </div>-->

              <!--                <div style="display: inline-block ; margin-left: 1%">-->
              <!--                  <h3 style="">-->
              <!--                    {{comment_user_list[index].username}}-->
              <!--                  </h3>-->
              <!--                </div>-->

              <!--                <div style="margin-left: 4.5%">-->
              <!--                  {{comment.content}}-->
              <!--                </div>-->

              <!--                <v-divider style=""></v-divider>-->

              <!--              </div>-->

              <v-list three-line v-if="comment_list[0] != null">
                <div>
                  <template v-for="(item, index) in this.comment_list">
                    <v-list-item :key="index">
                      <v-list-item-avatar color="primary" rounded>
                        <v-img
                          v-if="comment_user_list[index].avatar !== null"
                          :src="
                            'http://api.dreamhub.moyunbook.xyz' +
                            comment_user_list[index].avatar
                          "
                        ></v-img>
                      </v-list-item-avatar>

                      <v-list-item-content>
                        <v-list-item-title style="font-size: 22px">{{
                          comment_user_list[index].username
                        }}</v-list-item-title>
                        <v-list-item-subtitle
                          v-html="item.content"
                        ></v-list-item-subtitle>
                      </v-list-item-content>

                      <div>
                        <v-icon
                          v-if="user_like_status[index] === 1"
                          style="color: mediumpurple"
                          class="thumbUp"
                          @click="likeComment(item, 0, index)"
                        >
                          {{ icons.mdiThumbUp }}
                        </v-icon>

                        <v-icon
                          v-else
                          class="thumbUp"
                          @click="likeComment(item, 1, index)"
                        >
                          {{ icons.mdiThumbUp }}
                        </v-icon>

                        <div style="font-size: 15px">{{ item.likes }}</div>
                      </div>
                    </v-list-item>

                    <v-divider :key="index"></v-divider>
                  </template>
                </div>
              </v-list>

              <h2 v-else style="text-align: center">暂无相关评论！</h2>

              <h1 style="margin-top: 2%">发表评论</h1>

              <v-textarea
                v-model="comment_text"
                style="margin-top: 0.5%"
                auto-grow
                rows="3"
                row-height="15"
                outlined
                placeholder="请在此输入评论"
              >
              </v-textarea>
              <v-btn
                style="
                  float: right;
                  background-color: mediumpurple;
                  color: white;
                  margin-bottom: 2%;
                "
                @click="submitComment"
              >
                提交
              </v-btn>
            </div>
          </v-tab-item>
          <v-tab-item class="content">
            <h2 style="margin: 10px">带着10个问题去阅读和思考</h2>
            <div v-for="(seq, index) in seqs" :key="index">
              <h3 style="margin: 10px">Q{{ index + 1 }}</h3>
              <span style="margin-left: 30px;">{{ seq }}</span>
              <v-divider></v-divider>
            </div>
          </v-tab-item>
        </v-tabs>
      </div>
    </div>
  </div>
</template>

<script>
import axios from "axios";
import { mdiComment, mdiThumbUp, mdiComma } from "@mdi/js";
import pdf from "vue-pdf";
import 'katex/dist/katex.min.css';
import authorization from "../api/authorization";

export default {
  name: "PaperDetail",
  components: { pdf
  },
  data() {
    return {
      origin:{
        flag: false,
        gte: null,
        lte: null,
      },
      condFirst: {
        key : "标题",
        content: null,
      },
      condList: {
        list:[]
      },
      condListRe: {
        list: [],
      },
      searchStatus: {
        searchType: 0,
        offset: 0
      },
      keyword:{
        index:null,
        flag: false,
        keyword: null,
      },
      author_org:{
        index:null,
        flag: false,
        org_id: null,
      },
      res : null,
      cite : [],
      seqs: [
        "What is the problem addressed in the paper?",
        "Is this a new problem?",
        "What is the scientific hypothesis that the paper istrying to verifv ?",
        "What are the key related works and who are the key people working on this topic ?",
        "What is the key of the proposed solution in thepaper?",
        "How are the experiments designed?",
        "What datasets are built/used for the quantitativeevaluation ? Is the code open sourced ?",
        "Is the scientific hypothesis well supported byevidence in the experiments ?",
        "What are the contributions of the paper?",
        "What should/could be done next?",
      ],
      pageNum: 1,
      pageTotalNum: 1,
      loadedRatio: 0,
      id: this.$route.params.id,
      view_num: this.$route.params.view_num,
      username: localStorage.getItem("username"),
      readTimes: 331,
      items: ["预览PDF", "引用论文", "评论区", "论文速读"],
      tab: null,
      paper: [],
      comment_text: "", // 评论内容
      icons: {
        mdiComment,
        mdiThumbUp,
        mdiComma,
      },
      comment_list: [], // 当前paper评论列表
      comment_user_list: [], // 发表评论的用户列表
      status: [], // 后端返回的点赞状态列表
      user_like_status: [],
      is_collected: false,
      collection_id: null,
      dialog: false,
      hasLogin: null,
    };
  },
  mounted() {
    // console.log(this.$route.params.id)
    this.searchById();
    this.getComments();
    this.getLikesList();
    this.initIsCollected();
    this.getCite();
  },
  methods: {
    searchHandle() {
      var title = this.condFirst.content;
      console.log(this.condFirst)
      var flag = false
      for (let i = 0; i < this.condList.list.length; i ++) {
        if(this.condList.list[i][2]) {
          flag = true;
          break;
        }
      }
      console.log(title)
      if(!title && !flag) {
        // console.log(title);
        return;
      }
      const that = this;
      this.$api.aminerSearch.decode(this.searchStatus, this.origin, this.keyword, this.author_org, this.condFirst, this.condList)
          .then(function (response){
            that.res = response
            console.log(that.res)
            let routeData = that.$router.resolve({
              path: '/searchResults',
              query:{
                str:that.res.str,
              }
            })
            window.open(routeData.href, '_blank');

            // that.$router.push({
            //   path: '/searchResults',
            //   query:{
            //     str:that.res.str,
            //   }
            // })
          })

    },
    advancedSearch(){
      this.searchHandle()
    },
    keywordSearch(str) {
      this.condFirst.key = "标题"
      this.condFirst.content = str
      this.advancedSearch()
      // this.$router.push({ name: "searchResults", params: { text: str } });
    },
    getCite() {
      axios.get(
          '/api/scholar/paper/cite/' + this.id + '/',
      )
      .then (
          (response) => {
            console.log(response.data);
            this.cite = response.data;
          }
      )
    },
    toPaperDetail(item) {
      console.log(item.id);
      this.$router.push({
        name: "PaperDetail",
        params: {
          id: item.id,
          view_num: 0,
        },
      });
      location.reload();
    },
    initIsCollected() {

      const that = this;
      authorization().then(function (response) {
        // console.log(response[0]);
        that.hasLogin = response[0];
        if (response[0]) {
          axios
              .get("/api/collection/?sortby=create_time", {
                headers: {
                  Authorization: "Bearer " + localStorage.getItem("access"),
                },
              })
              .then((response) => {
                // console.log("ppp");
                console.log(response.data);
                for (let i = 0; i < response.data.results.length; i++) {
                  console.log("pp");
                  if (that.id === response.data.results[i].paper) {
                    that.is_collected = true;
                    that.collection_id = response.data.results[i].id;
                  }
                }
              });
        }
        // else {
        //   this.$notify.error({
        //     title: "请先登录！",
        //   });
        // }
      });


    },
    //获取当前用户对当前paper每条评论的点赞状态
    getLikesList() {
      const that = this;
      authorization().then(function (response) {
        if (response[0]) {
          axios
              .get("/api/scholar/paper/comment/" + that.id + "/like/", {
              })
              .then((response) => {
                console.log("q");
                that.status = response.data;
                console.log(that.status);
              });
        }
        else {
          that.status = [];
        }
      });
    },

    initLikesList() {
      console.log("xxx");
      for (let i = 0; i < this.comment_list.length; i++) {
        console.log("111");
        console.log(this.status);
        let flag = false;
        for (let j = 0; j < this.status.length; j++) {
          console.log("222");
          if (this.comment_list[i].id === this.status[j].comment) {
            console.log(this.status[j]);
            flag = true;
          }
          console.log(flag);
        }
        if (flag) this.user_like_status.push(1);
        else this.user_like_status.push(0);
      }
      // alert(this.status);
    },
    // 点赞
    likeComment(comment, status, index) {
      const that = this;
      authorization().then(function (response) {
        if (response[0]) {
          axios
              .post(
                  "/api/scholar/paper/comment/" + that.id + "/like/",
                  {
                    id: comment.id,
                    status: status,
                    likes: status === 1 ? comment.likes + 1 : comment.likes - 1,
                  },

              )
              .then((response) => {
                console.log(response);
                that.user_like_status[index] = status;
                if (status === 1) that.comment_list[index].likes++;
                else that.comment_list[index].likes--;
              });
        }
        else {
          that.$notify.error({
            title: "请先登录!",
          });
        }
      });



    },
    // 上一页
    prePage() {
      let page = this.pageNum;
      page = page > 1 ? page - 1 : this.pageTotalNum;
      this.pageNum = page;
    },

    // 下一页
    nextPage() {
      let page = this.pageNum;
      page = page < this.pageTotalNum ? page + 1 : 1;
      this.pageNum = page;
    },
    // 获取当前文献的详细信息
    searchById() {
      axios
        .get("/api/scholar/paper/" + this.id + "/")
        .then((response) => {
          this.paper = response.data;
          console.log(this.paper);
        })
        .catch(function (error) {
          alert(error);
        });
    },
    // 跳转pdf页面
    ToPDF() {
      let url = this.paper.pdf;
        window.open(url);
      // console.log(url);
      // window.location.href = url;
    },
    // 获取当前文献评论列表
    getComments() {
      axios
        .get("/api/scholar/paper/comment/" + this.id + "/")
        .then((response) => {
          this.comment_list = response.data.comments;
          this.comment_user_list = response.data.user_info;
          // console.log(response.data);
        });
    },
    //提交评论
    submitComment() {
      if (this.comment_text === "") {
        this.$notify.error({
          title: "评论不能为空！",
        });
        return;
      }
      const that = this;
      authorization().then(function (response) {
        that.hasLogin = response[0];
        if (response[0]) {
          axios
              .post(
                  "/api/scholar/paper/comment/" + that.id + "/",
                  {
                    content: that.comment_text,
                  },
              )
              .then((response) => {
                that.comment_list = response.data.comments;
                that.comment_user_list = response.data.user_info;
                that.user_like_status.push(0);
                console.log(response.data.comments);
              })
              .catch((error) => {
                this.$notify.error({
                  title: "",
                  message: error.message,
                });
              });
        }
        else {
          that.$notify.error({
            title: "请先登录!",
          });
        }
      });



    },
    // 收藏论文
    collect() {
      const that = this;
      authorization().then(function (response) {
        if (response[0]) {
          axios
              .post(
                  "/api/collection/",
                  {
                    paper: that.id,
                  },

              )
              .then((response) => {
                console.log(response.data);
                that.is_collected = true;
                that.initIsCollected();
                that.$notify.success({
                  title: "已添加至收藏夹！",
                });
              })
              .catch((error) => {
                that.$notify.error({
                  title: "收藏失败!",
                  message: error.message,
                });
              });
        }
        else {
          that.$notify.error({
            title: "请先登录!",
          });
        }
      });
    },
    // 取消收藏
    remove_collect() {
      axios
        .delete("/api/collection/" + this.collection_id + "/", )
        .then((response) => {
          console.log(response.data);
          this.is_collected = false;
          this.initIsCollected();
          this.$notify.success({
            title: "已移出收藏夹！",
          });
        })
        .catch((error) => {
          this.$notify.error({
            title: "取消收藏失败!",
            message: error.message,
          });
        });
    },
    // 跳转到学者主页
    ToUserPage(author) {
      if (author.id === undefined) {
        this.$notify.error({
          title: "搜索学者（开发中）",
          message: name,
        });
      } else {
        this.$router.push({ path: "/profile/" + author.id });
        window.location.reload(false);
      }
    },
  },
};
</script>

<style scoped>
.main {
  margin: 0 auto;
  width: 90%;
  background-color: white;
  border-radius: 10px;
  min-height: 1200px !important;
}

.line0 {
  margin-top: 1%;
}

.line1 {
  font-size: 10px;
  padding-top: 0.2%;
  margin-top: 0.5%;
}

.line2 {
  margin-top: 1%;
}

.line3 {
  margin-top: 2%;
}

.line4 {
  margin-top: 2%;
}

.title {
  color: #131120;
  font-size: 35px !important;
}

.keyword_btn {
  margin-right: 0.5%;
  margin-top: 0.5%;
}

.thumbUp:hover {
  cursor: pointer;
  /*color: mediumpurple;*/
}

.author:hover {
  color: mediumpurple;
  cursor: pointer;
}

.author_of_references {
  color: green;
}

.author_of_references:hover {
  cursor: pointer;
  color: darkgreen;
}

.title_of_reference {
  color: mediumpurple;
}

.title_of_reference:hover {
  cursor: pointer;
  color: purple;
}
.content{
  color: black;
}
</style>